import { useAuthStore } from '@/store/auth'
import { http } from '@/utils/http'
import { defineStore } from 'pinia'
import { ref } from 'vue'

const initState = { username: '默认用户', avatarUrl: '/static/images/default_avatar.png' }

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState })

    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }

    const clearUserInfo = () => {
      const { resetToken } = useAuthStore()
      userInfo.value = { ...initState }
      resetToken()
    }

    const login = async (data: ILoginUser) => {
      const { setToken } = useAuthStore()
      const { result } = await http.post<IUserInfo>('/auth/login', data, null, false)
      setUserInfo(result)
      setToken(result.accessToken)
      setTimeout(() => {
        uni.reLaunch({ url: '/pages/mine/mine' })
      }, 500)
    }

    const isLogined = computed(() => {
      const { accessToken } = useAuthStore()
      return accessToken !== null
    })

    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      isLogined,
      login,
    }
  },
  {
    persist: true,
  },
)
